#define _CRT_SECURE_NO_WARNINGS 1
#include "Stack.h"
void StackInit(stack* ps)
{
	assert(ps);
	ps->a = NULL;
	ps->top = 0;
	ps->capacity = 0;
}
void StackPush(stack* ps, DataType x)
{
	assert(ps);
	//检查容量
	if (ps->capacity == ps->top)
	{
		int newcapacity = ps->capacity == 0 ? 4 : (ps->capacity) * 2;
		DataType* tmp = (DataType*)realloc(ps->a, sizeof(stack) * newcapacity);//realloc如果是空指针，则该函数的行为类似于malloc
		if (tmp == NULL)
		{
			perror("realloc fail");
			exit(-1);
		}
		ps->a = tmp;
		ps->capacity = newcapacity;
	}

	//入栈
	ps->a[ps->top] = x;
	ps->top++;

}

void StackPop(stack* ps)
{
	assert(ps);
	assert(ps->top > 0);
	--(ps->top);
}
DataType StackTop(stack* ps)
{
	assert(ps);
	//栈顶元素是top前一个
	return ps->a[ps->top-1];
}

int StackSize(stack* ps)
{
	assert(ps);
	return ps->top;
}
bool StackEmpty(stack* ps)
{
	assert(ps);
	return ps->top == 0 ? true : false;
}

void StackDestory(stack* ps)
{
	assert(ps);
	free(ps->a);
	ps->a == NULL;
	ps->capacity = ps->top = 0;
}